<template>
  <view class="container">
    <!-- 用户信息 -->
    <view class="user-info">
      <!-- {{ userState.user_info }} -->
      <!-- <image class="avatar" :src="(userState.user_info.avatar || '/static/images/default-avatar.png').startsWith('http') ? userState.avatar || '/static/images/default-avatar.png' : `${config.apiBaseUrl}${userState.avatar || '/static/images/default-avatar.png'}`" mode="aspectFill" @tap="showEditModal"></image> -->
      <image class="avatar" :src="(userState.user_info.avatar || '/static/images/default-avatar.png').startsWith('http') ? userState.user_info.avatar || '/static/images/default-avatar.png' : `${config.apiBaseUrl}${userState.user_info.avatar || '/static/images/default-avatar.png'}`" mode="aspectFill" @tap="showEditModal"></image>
      <view class="user-detail">
        <text class="username">{{ userState.nickname || '未登录' }}</text>
        <text class="user-tag" :class="userState.vipLevel">{{ userState.vipLevel === 'FREE' ? '免费用户' : 'VIP会员' }}</text>
      </view>
      <text v-if="userState.vipLevel === 'FREE'" class="coins">剩余次数：{{ userState.usage.remaining_count || 0 }}</text>
    </view>

    <!-- VIP激活码输入 -->
    <view class="vip-activate" v-if="userState.id">
      <view class="activate-input">
        <input type="text" v-model="activateCode" placeholder="请输入VIP激活码" />
        <button class="activate-btn" @tap="handleActivate">激活</button>
      </view>
    </view>

    <!-- 会员信息 -->
    <view class="vip-info" v-if="userState.id && vipInfo.is_vip">
      <view class="vip-header">
        <text class="vip-title">{{ vipInfo.vip_type_display }}</text>
        <text class="vip-status">已激活</text>
      </view>
      <view class="vip-time">
        <text>有效期：{{ formatTime(vipInfo.start_time) }} 至 {{ formatTime(vipInfo.end_time) }}</text>
      </view>
    </view>

    <!-- 常用功能 -->
    <view class="common-features">
      <view class="section-title">常用功能</view>
      <view class="features-grid">
        <view class="feature-item" @tap="handleHistory">
          <text class="feature-icon">📝</text>
          <text class="feature-name">配音历史</text>
        </view>
        <!-- <view class="feature-item" @tap="handleFavorites">
          <text class="feature-icon">⭐</text>
          <text class="feature-name">我的收藏</text>
        </view> -->
        <!-- <view class="feature-item" @tap="handleUpgrade" v-if="userState.vipLevel === 'FREE'">
          <text class="feature-icon">👑</text>
          <text class="feature-name">开通会员</text>
        </view> -->
        <!-- <view class="feature-item" @tap="handleFeedback">
          <text class="feature-icon">💬</text>
          <text class="feature-name">意见反馈</text>
        </view> -->
        <view class="feature-item" @tap="handleAbout">
          <text class="feature-icon">ℹ️</text>
          <text class="feature-name">关于我们</text>
        </view>
      </view>
    </view>

    <!-- 更多功能 -->
    <view class="more-features">
      <view class="section-title">更多功能</view>
      <view class="feature-list">
        <!-- <view class="feature-list-item" @tap="handleSettings">
          <text class="feature-icon">⚙️</text>
          <text class="feature-name">设置</text>
          <text class="arrow">></text>
        </view> -->
        <view class="feature-list-item" @tap="handleVipInfo" v-if="userState.vipLevel !== 'FREE'">
          <tts-icons type="huiyuan" size="40" color="#f9cf7e" ></tts-icons>
          <text class="feature-name">会员信息</text>
          <tts-icons type="youbianjiantou" size="30" color="#ddd" />
        </view>
        <!-- <view class="feature-list-item" @tap="handleLogout" v-if="userState.isLoggedIn">
          <text class="feature-icon">🚪</text>
          <text class="feature-name">退出登录</text>
          <text class="arrow">></text>
        </view> -->
        <!-- 客服按钮 -->
        <button class="feature-list-item customer-service-btn" @tap="sendMessage" open-type="contact">
          <view class="feature-list-item-content">
            <tts-icons type="kefu" size="40" color="#07c160" />
            <text style="margin-left: 10rpx;" class="feature-name">联系客服</text>
          </view>
          
          <tts-icons type="youbianjiantou" size="30" color="#ddd" />
        </button>
      </view>
    </view>

    <!-- 版本信息 -->
    <view class="version-info">
      <text class="version-text">优声配音 v1.0.0</text>
      <!-- <text class="usage-text">配音 5 年超 2 亿次</text> -->
    </view>
    
    <!-- 修改用户信息弹窗 -->
    <view class="modal-overlay" v-if="showEditModalFlag" @tap="closeEditModal">
      <view class="edit-modal" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">修改用户信息</text>
          <text class="close-btn" @tap="closeEditModal">×</text>
        </view>
        <view class="modal-content">
          <view class="avatar-section" @tap="chooseLocalAvatar">
            <image class="preview-avatar" :src="(editForm.avatar || userState.avatar || '/static/images/default-avatar.png').startsWith('http') ? (editForm.avatar || userState.avatar || '/static/images/default-avatar.png') : `${config.apiBaseUrl}${editForm.avatar || userState.avatar || '/static/images/default-avatar.png'}`" mode="aspectFill" ></image>
            <text class="avatar-tip">点击修改头像</text>
          </view>
          <view class="form-item">
            <text class="form-label">昵称</text>
            <input class="form-input" type="text" v-model="editForm.nickname" placeholder="请输入昵称" />
          </view>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @tap="closeEditModal">取消</button>
          <button class="confirm-btn" @tap="handleUpdateUserInfo">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { userState } from '@/services/user'
import { getUserInfo, logout } from '@/services/auth'
import config from '@/config'
import { sendCustomerServiceMessage } from '@/services/auth'

// 发送消息
function sendMessage() {
	sendCustomerServiceMessage({
		content: '你好，我想咨询一下配音服务'
	})
}

// 编辑表单
const editForm = ref({
  nickname: '',
  avatar: ''
})

// 弹窗显示状态
const showEditModalFlag = ref(false)

// VIP激活相关
const activateCode = ref('')
const vipInfo = ref({
	is_vip: false,
	vip_type: null,
	vip_type_display: null,
	start_time: null,
	end_time: null
})

// 显示编辑弹窗
function showEditModal() {
  if (!userState.value.isLoggedIn) return
  
  // 初始化表单数据
  editForm.value = {
    nickname: userState.value.user_info.nickname || '',
    avatar: userState.value.user_info.avatar  || ''
  }
  
  showEditModalFlag.value = true
}

// 关闭编辑弹窗
function closeEditModal() {
  showEditModalFlag.value = false
}

// 选择本地头像
function chooseLocalAvatar() {
	uni.chooseImage({
		count: 1,
		success: async (res) => {
			try {
				uni.showLoading({
					title: '上传中...',
					mask: true
				})
				
				// 上传图片到服务器
				const ress = await uni.uploadFile({
					url: `${config.apiBaseUrl}/api/upload/image`,
					filePath: res.tempFilePaths[0],
					name: 'image',
					header: {
						'Authorization': uni.getStorageSync('token')
					}
				})
				console.log({ress});
        
				
				
				const result = JSON.parse(ress.data)
        console.log({result});
        
				if (result.code !== 200) {
					throw new Error(result.message || '上传失败')
				}
				
				// 更新头像地址
				editForm.value.avatar = result.data.url
				
				uni.hideLoading()
				uni.showToast({
					title: '上传成功',
					icon: 'success'
				})
			} catch (error) {
				uni.hideLoading()
				uni.showToast({
					title: error.message || '上传失败，请重试',
					icon: 'none'
				})
			}
		}
	})
}

// 更新用户信息
async function handleUpdateUserInfo() {
  try {
    uni.showLoading({
      title: '更新中...',
      mask: true
    })
    
    const token = uni.getStorageSync('token')
    if (!token) {
      throw new Error('未登录')
    }
    
    const result = await uni.request({
      url: `${config.apiBaseUrl}/api/wechat/user/update`,
      method: 'POST',
      header: {
        'Authorization': token
      },
      data: editForm.value
    })
    
    if (result.statusCode !== 200 || result.data.code !== 200) {
      throw new Error(result.data.message || '更新失败')
    }
    
    // 更新本地用户状态
    // Object.assign(userState.value, result.data.data)
    fetchUserInfo()
    
    uni.hideLoading()
    uni.showToast({
      title: '更新成功',
      icon: 'success'
    })
    
    closeEditModal()
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '更新失败，请重试',
      icon: 'none'
    })
  }
}

// 获取用户信息
async function fetchUserInfo() {
  try {
    await getUserInfo()
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取会员信息
async function fetchVipInfo() {
	try {
		const token = uni.getStorageSync('token')
		if (!token) {
			return
		}
		
		const result = await uni.request({
			url: `${config.apiBaseUrl}/api/vip/info`,
			method: 'GET',
			header: {
				'Authorization': token
			}
		})
		
		if (result.statusCode !== 200 || result.data.code !== 200) {
			throw new Error(result.data.message || '获取会员信息失败')
		}
		console.log({result});
		
		// 更新VIP信息
		vipInfo.value = result.data.data
		
		// 更新用户状态中的VIP信息
		if (userState.value) {
			userState.value.vipLevel = vipInfo.value.is_vip ? 'VIP' : 'FREE'
		}
	} catch (error) {
		console.error('获取会员信息失败:', error)
	}
}

// 处理配音历史
function handleHistory() {
  uni.navigateTo({
    url: '/pages/history/index'
  })
}

// 处理我的收藏
function handleFavorites() {
  uni.navigateTo({
    url: '/pages/favorites/index'
  })
}

// 处理开通会员
function handleUpgrade() {
  uni.navigateTo({
    url: '/pages/vip/index'
  })
}

// 处理意见反馈
function handleFeedback() {
  uni.navigateTo({
    url: '/pages/feedback/index'
  })
}

// 处理关于我们
function handleAbout() {
  uni.navigateTo({
    url: '/pages/about/index'
  })
}

// 处理设置
function handleSettings() {
  uni.navigateTo({
    url: '/pages/settings/index'
  })
}

// 处理会员信息
function handleVipInfo() {
  uni.navigateTo({
    url: '/pages/vip/info'
  })
}

// 处理退出登录
function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        logout()
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
      }
    }
  })
}

// 激活VIP
async function handleActivate() {
	if (!activateCode.value) {
		uni.showToast({
			title: '请输入激活码',
			icon: 'none'
		})
		return
	}
	
	try {
		const token = uni.getStorageSync('token')
		if (!token) {
			throw new Error('未登录')
		}
		
		const result = await uni.request({
			url: `${config.apiBaseUrl}/api/vip/activate`,
			method: 'POST',
			header: {
				'Authorization': token
			},
			data: {
				code: activateCode.value
			}
		})
		console.log({result});
		
		if (result.statusCode !== 200 || result.data.code !== 200) {
			throw new Error(result.data.message || '激活失败')
		}
		
		uni.showToast({
			title: '激活成功',
			icon: 'success'
		})
		
		// 清空激活码
		activateCode.value = ''
		
		// 刷新会员信息
		await fetchVipInfo()
	} catch (error) {
		uni.showToast({
			title: error.message || '激活失败，请重试',
			icon: 'none'
		})
	}
}

// 格式化时间
function formatTime(timestamp) {
	if (!timestamp) return ''
	const date = new Date(timestamp)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}`
}

// 页面加载时获取用户信息和会员信息
onMounted(() => {
	fetchUserInfo()
	fetchVipInfo()
})
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  background: #f8f8f8;
  min-height: 100vh;
}

.user-info {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-detail {
  flex: 1;
  
  .username {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .user-tag {
    font-size: 24rpx;
    color: #fff;
    padding: 4rpx 12rpx;
    border-radius: 6rpx;
    
    &.FREE {
      background: #999;
    }
    
    &.VIP {
      background: #ffd700;
    }
    
    &.SVIP {
      background: linear-gradient(to right, #ff6b6b, #ff8e8e);
    }
  }
}

.coins {
  font-size: 28rpx;
  color: #666;
}

.common-features,
.more-features {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20rpx;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .feature-icon {
    font-size: 40rpx;
    margin-bottom: 10rpx;
  }
  
  .feature-name {
    font-size: 24rpx;
    color: #666;
  }
}

.feature-list {
  .feature-list-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .feature-icon {
      font-size: 36rpx;
      margin-right: 20rpx;
    }
				
    .feature-name {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .arrow {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.version-info {
  text-align: center;
  padding: 40rpx 0;
  
  .version-text {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .usage-text {
    font-size: 24rpx;
    color: #999;
  }
}

// 弹窗样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 999;
}

.edit-modal {
  width: 100%;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
  transform: translateY(0);
  transition: transform 0.3s ease-out;
  
  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      font-size: 40rpx;
      color: #999;
      padding: 0 20rpx;
    }
  }
  
  .modal-content {
    padding: 30rpx;
    
    .avatar-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 30rpx;
      
      .preview-avatar {
        width: 160rpx;
        height: 160rpx;
        border-radius: 80rpx;
        margin-bottom: 10rpx;
      }
      
      .avatar-tip {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .form-item {
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
        display: block;
      }
      
      .form-input {
        width: 100%;
        height: 80rpx;
        background: #f8f8f8;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
  
  .modal-footer {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-top: 1rpx solid #f5f5f5;
    
    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 30rpx;
      border-radius: 40rpx;
      margin: 0 10rpx;
      
      &:first-child {
        margin-left: 0;
      }
      
      &:last-child {
        margin-right: 0;
      }
    }
    
    .cancel-btn {
      background: #f5f5f5;
      color: #666;
    }
    
    .confirm-btn {
      background: #07c160;
      color: #fff;
    }
  }
}

.vip-activate {
	margin: 20rpx;
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	
	.activate-input {
		display: flex;
		align-items: center;
		gap: 20rpx;
		
		input {
			flex: 1;
			height: 80rpx;
			background: #f8f8f8;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
		}
		
		.activate-btn {
			width: 160rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #07c160;
			color: #fff;
			border-radius: 8rpx;
			font-size: 28rpx;
			
			&:active {
				opacity: 0.8;
			}
		}
	}
}

.vip-info {
	margin: 20rpx;
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	
	.vip-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		.vip-title {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
		}
		
		.vip-status {
			font-size: 24rpx;
			color: #07c160;
			background: rgba(7, 193, 96, 0.1);
			padding: 4rpx 16rpx;
			border-radius: 20rpx;
		}
	}
	
	.vip-time {
		font-size: 24rpx;
		color: #999;
	}
}

.customer-service-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100rpx;
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  line-height: 1;
  .feature-list-item-content {
    display: flex;
    align-items: center;
  }
  &::after {
    border: none;
  }
  
  &:active {
    opacity: 0.8;
  }
}
</style> 